package com.start.boot.web;


import com.start.boot.common.SystemConfiguration;
import com.start.boot.domain.*;
import com.start.boot.service.OriganizationService;
import com.start.boot.support.utils.AjaxHelper;
import com.start.boot.support.utils.EasyUIHelper;
import com.start.boot.support.utils.FastJsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 组织机构管理控制器
 * Created by lenovo on 2017/10/25.
 */

@RestController
@RequestMapping("/organization")
public class OriganizationController extends ArchivesSystemBaseController {


    @Autowired
    private OriganizationService origanizationService;

    /**
     * 获取单位树(获取本单位及下级单位)
     */
    @RequestMapping("/GetDwbmTree")
    public String getGetDwbmTree() {

        //获取单位编码
        String dwbm = getCurrentDwbm();

        //判断用户是否是登陆，从配置文件中获取
        if (dwbm == null || StringUtils.isEmpty(dwbm)) {
            dwbm = SystemConfiguration.djdwbm;
        }

        //传入单位编码，返回结果集
        Map map = new HashMap();
        map.put("p_dwbm",dwbm);

       origanizationService.getDwbm(map);

       //数据库要获取的数据：
        List<Map> list = (List<Map>) map.get("p_cursor");

        if (list == null) {
            super.errMsg("获取单位树失败",null,new Exception("获取单位树失败"));
            return null;
        }

        String topBM = "";
        //遍历集合，找到本单位的父单位
        for (int i = 0; i < list.size(); i++) {
                Map<String,String> resultMap = list.get(i);
                for ( String key: resultMap.keySet()) {
                        if (key.equals("BM") && resultMap.get(key).equals(dwbm)) {
                            topBM = resultMap.get("FBM");
                            break;
                        }
            }
        }

        //转为EasyUI结构：
        return  EasyUIHelper.buildTreeDataSourceWithoutIconCol(list, "BM", "FBM", "MC", topBM);
    }


    /**
     *  获取组织结构树(单位部门角色)
     * @return
     */
    @RequestMapping(value = "/GetDwBmJsByDwbm")
    public String GetDwBmJsByDwbm( String dwbm) {

        Map map = new HashMap();
        map.put("p_dwbm",dwbm);
        origanizationService.getDwBmJsInfoByDwBm(map);

        List<Map> list = (List<Map>) map.get("p_cursor");
        if (list.size() == 0) {
            super.errMsg("获取组织结构结构树失败",dwbm,new Exception("获取组织结构结构树失败"));
        }

        String topBM = "";
        //遍历集合，找到本单位的父单位
        for (int i = 0; i < list.size(); i++) {
            Map<String,String> resultMap = list.get(i);
            for ( String key: resultMap.keySet()) {
                if (key.equals("BM") && resultMap.get(key).equals(dwbm)) {
                    topBM = resultMap.get("FBM");
                    break;

                }
            }
        }

        //转为EasyUI结构：
        String s = EasyUIHelper.buildTreeListDataSource(list, "BM", "FBM", "MC", "ICON", topBM);

        return s;
    }

    /**
     *  添加部门/编辑部门
     * @return
     */
    @RequestMapping("/AddBmInfo")
    public String AddBmInfo() throws IOException {

        //接受json字符串，并解析为对象
        String json = getParameter("json");
        Bmbm param = FastJsonUtils.toObject(Bmbm.class, json);

        //封装map，调用存储过程
        Map map = new HashMap();
        map.put("p_dwbm", param.getDWBM());
        map.put("p_bmbm", param.getBMBM());
        map.put("p_bmmc", param.getBMMC());
        map.put("p_bmjc", param.getBMJC());
        map.put("p_bmxh", param.getBMXH());
        map.put("p_bz", param.getBZ());
        map.put("p_fbmbm", param.getFBMBM());

        origanizationService.AddBmInfo(map);

        String bmbm = (String) map.get("p_bmbm");
        String ErrMsg = (String) map.get("p_errmsg");
        //创建结果包装对象

        if (ErrMsg != null || bmbm ==null) {
            super.errMsg("添加/更新部门失败",param.toString(),new Exception("添加/更新失败"));
        }

        String s = AjaxHelper.buildResponseDataSource(ErrMsg, bmbm);
        return s;
    }


    /**
     * 获取部门信息
     */
    @RequestMapping("/GetBmInfo")
    public String GetBmInfo() {

        String dwbm = getParameter("dwbm");
        String bmbm = getParameter("bmbm");

        Map map = new HashMap();
        map.put("p_dwbm",dwbm);
        map.put("p_bmbm",bmbm);

        origanizationService.GetBmInfo(map);
        String p_errmsg = (String) map.get("p_errmsg");

        if (p_errmsg != null) {
            super.errMsg("获取部门信息出错",dwbm.toString(),new Exception("获取部门信息出错"));
        }

        List<Bmbm> list = (List<Bmbm>) map.get("p_cursor");
        Bmbm bmInfo=null;
        if (list.size() != 0) {
             bmInfo = (Bmbm) list.get(0);
        }

         return   AjaxHelper.buildResponseDataSource(p_errmsg,bmInfo);

    }


    /**
     * 删除部门
     */
    @RequestMapping("/DeleteBmInfo")
    public String DeleteBmInfo() {

        String bmbm = getParameter("bmbm");
        String dwbm = getParameter("dwbm");

        Map map = new HashMap();
        map.put("p_dwbm",dwbm);
        map.put("p_bmbm",bmbm);

        origanizationService.DeleteBmInfo(map);

        String p_errmsg = (String) map.get("p_errmsg");

        if (p_errmsg != null) {
            super.errMsg("删除部门失败",map.toString(),new Exception("删除部门失败"));
        }

        return AjaxHelper.buildResponseDataSource(p_errmsg,p_errmsg == null);
    }


    /**
     * 添加/修改角色
     */
    @RequestMapping("/AddJsInfo")
    public  String AddJsInfo() {

        //接受json字符串，并解析为对象
        String json = getParameter("json");
        Jsbm jsbm = FastJsonUtils.toObject(Jsbm.class, json);

        Map map = new HashMap();
        map.put("p_dwbm", jsbm.getDwbm());
        map.put("p_bmbm", jsbm.getBmbm());
        map.put("p_jsbm", jsbm.getJsbm());
        map.put("p_jsmc", jsbm.getJsmc());
        map.put("p_jsxh", jsbm.getJsxh());
        map.put("p_jsbm", jsbm.getJsbm());

        origanizationService.AddJsInfo(map);

        String p_errmsg = (String) map.get("p_errmsg");
        if (p_errmsg != null) {
            super.errMsg("修改/添加角色失败",jsbm.toString(),new Exception("修改/添加角色失败"));
        }

        return AjaxHelper.buildResponseDataSource(p_errmsg,p_errmsg == "");
    }


    /**
     * 获取人员信息
     * @return
     */
    @RequestMapping("/GetRyInfo")
    public String GetRyInfo( String json) {

        //获取当前页大小与页面
        int page = parsePage(getParameter("page"));
        int rows = parseRows(getParameter("rows"));

        //将json对象转为实体类
        Param_rybm param_rybm = FastJsonUtils.toObject(Param_rybm.class, json);
        if (param_rybm == null) {
            return null;
        }
        Map map = new HashMap();
        map.put("p_dwbm",param_rybm.getDwbm());
        map.put("p_bmbm",param_rybm.getBmbm());
        map.put("p_jsbm",param_rybm.getJsbm());
        map.put("p_gh",param_rybm.getGh());
        map.put("p_gzzh",param_rybm.getGzzh());
        map.put("p_xm",param_rybm.getXm());
        map.put("p_pagesize",rows);
        map.put("p_pageindex",page);

        origanizationService.GetRyInfo(map);

        String p_errmsg = (String) map.get("p_errmsg");
        if (p_errmsg != null) {
            super.errMsg("获取人员信息失败",json,new Exception("获取人员信息失败"));
            return null;
        }

        List<Map> list = (List<Map>) map.get("p_cursor");
        Integer p_count = (Integer) map.get("p_count");
        return EasyUIHelper.buildDataGridDataSource(list,p_count);

    }

    /**
     * 获取角色信息
     */
    @RequestMapping("/GetJsxh")
    public String GetJsxh(Jsbm jsbm) {

        Map map = new HashMap();
        map.put("p_dwbm", jsbm.getDwbm());
        map.put("p_bmbm", jsbm.getBmbm());
        map.put("p_jsbm", jsbm.getJsbm());
        origanizationService.GetJsxh(map);

        //获取数据：
        List<Jsbm> p_cursor = (List<Jsbm>) map.get("p_cursor");
        String p_errmsg = (String) map.get("p_errmsg");

        if (p_errmsg != null || p_cursor.size() == 0) {
             super.errMsg("获取角色信息失败",jsbm.toString(),new Exception("获取角色失败"));
        }

        Integer xh = p_cursor.get(0).getJsxh();

        return  AjaxHelper.buildResponseDataSource(p_errmsg,xh);

    }

    /**
     * 删除角色
     * @param jsbm
     * @return
     */
    @RequestMapping("/DeleteJsInfo")
    public String DeleteJsInfo(Jsbm jsbm) {

        Map map = new HashMap();
        map.put("p_dwbm", jsbm.getDwbm());
        map.put("p_bmbm", jsbm.getBmbm());
        map.put("p_jsbm", jsbm.getJsbm());

        origanizationService.DeleteJsInfo(map);

        String p_errmsg = (String) map.get("p_errmsg");
        if (p_errmsg != null) {
            super.errMsg(p_errmsg.toString(),FastJsonUtils.toString(jsbm),new Exception("删除角色失败"));
        }

       return  AjaxHelper.buildResponseDataSource(p_errmsg,p_errmsg==null);

    }

    /**
     * 添加角色功能权限
     * @return
     */
    @RequestMapping("/AddJsgnfp")
    public String AddJsgnfp() {

        //解析json对象，转为实体类
        String json = getParameter("json");
        Jsgnfp jsgnfp = FastJsonUtils.toObject(Jsgnfp.class, json);
        if (jsgnfp != null || StringUtils.isNoneEmpty(jsgnfp.getGnbm()))
            jsgnfp.setGnbm(jsgnfp.getGnbm().substring(1));

        //封装map，调用存储过程
        Map map = new HashMap();
        map.put("p_dwbm",jsgnfp.getDwbm());
        map.put("p_bmbm",jsgnfp.getBmbm());
        map.put("p_jsbm",jsgnfp.getJsbm());
        map.put("p_gnbmj",jsgnfp.getGnbm());

        origanizationService.AddJsgnfp(map);

        String p_errmsg = (String) map.get("p_errmsg");
        if (p_errmsg != null) {
            super.errMsg("分配角色功能权限发生错误",FastJsonUtils.toString(jsgnfp),new Exception("分配角色功能权限发生错误"));
        }

       return  AjaxHelper.buildResponseDataSource(p_errmsg,p_errmsg==null);
    }

    /**
     * 获取角色功能权限列表
     * @param bmbm
     * @param jsbm
     * @param dwbm
     * @return
     */
    @RequestMapping("/GetJsGnqx")
    //bmbm=' + bmbm + '&jsbm=' + jsbm + '&dwbm=' + dwbm
    public String GetJsGnqx(@RequestParam("bmbm")String bmbm,@RequestParam("jsbm")String jsbm,@RequestParam("dwbm")String dwbm) {

        Map map = new HashMap();
        map.put("p_dwbm", dwbm);
        map.put("p_bmbm", bmbm);
        map.put("p_jsbm", jsbm);

        origanizationService.GetJsGnqx(map);

        List<Map> list = (List<Map>) map.get("p_cursor");
        Object p_errmsg = map.get("p_errmsg");

        if (p_errmsg != null) {
            super.errMsg("获取功能权限失败",map.toString(),new Exception("获取功能权限失败"));
        }

      return  EasyUIHelper.buildDataGridDataSource(list,list.size());

    }


    /**
     * 分配功能权限
     * @return
     */
    @RequestMapping("/AddDwGnQx")
    public String AddDwGnQx() {

        String dwbm = getParameter("dwbm");
        String gnbmj = getParameter("gnbmj");

        String errmsg = null;
        boolean isSuccess = false;
        //移除单位功能权限
        try {
            origanizationService.AddDwGnQx(dwbm,gnbmj);
            isSuccess = true;
        } catch (Exception e) {
            super.errMsg("分配功能权限失败",dwbm+""+gnbmj,e);
            errmsg = e.getMessage();
            e.printStackTrace();
        }
        return AjaxHelper.buildResponseDataSource(null,isSuccess);

    }


    /**
     * 未分配角色人员数据
     * @param json
     * @return
     */
    @RequestMapping("/GetWfpRyInfo")
    public  String GetWfpRyInfo( String json) {

        //获取当前页大小与页面
        int page = parsePage(getParameter("page"));
        int rows = parseRows(getParameter("rows"));

        Param_rybm param_rybm = FastJsonUtils.toObject(Param_rybm.class, json);

        Map map = new HashMap();
        map.put("p_dwbm",param_rybm.getDwbm());
        map.put("p_bmbm",param_rybm.getBmbm());
        map.put("p_jsbm",param_rybm.getJsbm());
        map.put("p_gh",param_rybm.getGh());
        map.put("p_gzzh",param_rybm.getGzzh());
        map.put("p_xm",param_rybm.getXm());
        map.put("p_pagesize",rows);
        map.put("p_pageindex",page);

        origanizationService.GetWfpRyInfo(map);
        Object p_errmsg = map.get("p_errmsg");
        if (p_errmsg != null) {
            super.errMsg("获取分配角色人员数据失败",FastJsonUtils.toString(map),new Exception("获取分配角色人员数据失败"));
        }
        List<Map> list = (List<Map>) map.get("p_cursor");
        Integer p_count = (Integer) map.get("p_count");
        return EasyUIHelper.buildDataGridDataSource(list,p_count);

    }


    /**
     *  加载单位功能权限列表
     * @param dwbm
     * @return
     */

    @RequestMapping("/GetAllGnqx")
    public String GetAllGnqx(@RequestParam("dwbm") String dwbm) {

      String  djdwbm= SystemConfiguration.djdwbm;

        String uerDwbm = (String) getSession().getAttribute("dwbm");
        if (StringUtils.isEmpty(uerDwbm) || StringUtils.isEmpty(dwbm)) {
            super.errMsg("加载单位功能权限列表",null,new Exception("加载单位功能权限列表"));
            return null;
        }

        Map map = new HashMap();
        map.put("p_dwbm",uerDwbm);
        map.put("p_xzdwbm",dwbm);
        map.put("p_djdwbm",djdwbm);
        origanizationService.GetAllGnqx(map);

        List<Map> list = (List<Map>) map.get("p_cursor");

        int total = 0;
        if (list != null) {
            total = list.size();
        }
        super.errMsg("加载单位功能权限列表",null,new Exception("加载单位功能权限列表"));

        return EasyUIHelper.buildDataGridDataSource(list,total);
    }

    /**
     * 添加人员
     * @return
     */
    @RequestMapping("/AddRYJSFP")
    @Transactional
    public String AddRYJSFP() {

        String errMsg = "";
        try{
            //获取人员信息，并解析为实体类
            String json = getParameter("json");
            List<Param_rybm> list = FastJsonUtils.toList(Param_rybm.class, json);

            //处理接受的数据：
            for (Param_rybm param : list) {
                Map map = new HashMap();

                map.put("p_dwbm", param.getDwbm());
                map.put("p_bmbm", param.getBmbm());
                map.put("p_jsbm", param.getJsbm());
                map.put("p_gh", param.getGh());
                map.put("p_ydwbm", param.getYdwbm());
                map.put("p_ydwmc", param.getYdwmc());
                map.put("p_ybmbm", param.getYbmbm());
                map.put("p_ybmmc", param.getYbmmc());
                map.put("p_yjsbm", param.getYjsbm());
                map.put("p_yjsmc", param.getYjsmc());

                origanizationService.AddRYJSFP(map);
                String p_errmsg = (String) map.get("p_errmsg");
                if (p_errmsg != null) {
                    throw new Exception(p_errmsg);
                }
            }
        }catch (Exception e){
            errMsg = e.getMessage();
        }

        return AjaxHelper.buildResponseDataSource(errMsg, errMsg==null?"添加人员成功":"添加人员信息失败");

    }


    /**
     * 人员调岗
     * @return
     */
    @RequestMapping("/TransJob")
    public  String TransJob() {
        //获取人员信息，并解析为实体类
        String json = getParameter("json");
        if (StringUtils.isEmpty(json)) {
            return null;
        }

        String errmsg=null;
        try {
        Param_TransJob param_transJob = FastJsonUtils.toObject(Param_TransJob.class, json);
            origanizationService.removeJob(param_transJob);
        } catch (Exception e) {
            errmsg=e.getMessage();
            super.errMsg("人员调岗失败",json,e);
            e.printStackTrace();
        }

        return AjaxHelper.buildResponseDataSource(errmsg,errmsg==null);
    }

    /**
     *  获取部门下角色列表
     * @param bmbm
     * @param dwbm
     * @return
     */
    @RequestMapping("/GetJSInfoByDwBm")
    public String GetJSInfoByDwBm(@RequestParam("bmbm")String bmbm,@RequestParam("dwbm")String dwbm) {

        //操作数据库
        Map map = new HashMap();
        map.put("p_dwbm", dwbm);
        map.put("p_bmbm", bmbm);

        //要获取的数据
            origanizationService.GetJSInfoByDwBm(map);

            List<Map>  list = (List<Map>) map.get("p_cursor");
            Object p_errmsg = map.get("p_errmsg");
        if (p_errmsg != null) {
              super.errMsg("获取人员调岗角色失败",map.toString(),new Exception("获取人员调岗角色失败"));
        }

        return EasyUIHelper.buildComboBoxDataSource(list, "BM", "MC" );


    }

    /**
     * 解除人员岗位
     * @return
     */
    @RequestMapping("/RemoveJob")
    public  String RemoveJob() {
        //获取Ajax传入参数：
        String json = getParameter("json");
        Param_TransJob param_transJob = FastJsonUtils.toObject(Param_TransJob.class, json);

        //执行操作数据库
        Map map = new HashMap();
        map.put("p_dwbm", param_transJob.getDWBM());
        map.put("p_bmbm", param_transJob.getBMBM());
        map.put("p_jsbm", param_transJob.getJSBM());
        map.put("p_gh", param_transJob.getRYGH());

        String errmsg = null;
        Boolean isSuccess = false;

        try {
            origanizationService.RemoveJob(map);
            isSuccess = true;
        } catch (Exception e) {
            super.errMsg("解除人员岗位失败",json,e);
            errmsg = e.getMessage();
            e.printStackTrace();
        }

        return AjaxHelper.buildResponseDataSource(errmsg,isSuccess);
    }

    /**
     * 获取部门编码
     * @param dwbm
     * @return
     */
    @RequestMapping("/getBmList")
    public String getBmList(@RequestParam("dwbm")String dwbm) {

        Map map = new HashMap();
        map.put("p_dwbm", dwbm);

        origanizationService.GetBMBM(map);
        String errmsg = (String) map.get("p_errmsg");
        if (StringUtils.isNotEmpty(errmsg)) {
            super.errMsg("获取部门编码失败",map.toString(),new Exception("获取部门编码失败"));
            return null;
        }
        List<Map> list = (List<Map>) map.get("p_cursor");
        return EasyUIHelper.buildComboBoxDataSource(list, "BM", "MC" );

    }


}
